package com.lizard.schedule.persistence.db.table;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.lizard.schedule.persistence.db.DbHelper;
import com.lizard.schedule.persistence.db.bean.DownloadFileInfo;

/**
 * 正在下载的目标文件信息表
 */
public class DownloadFileInfoTbl {

    private static DownloadFileInfoTbl instance;

    /**
     * 表名
     */
    private final String TBL_NAME = "e_tbl";

    /**
     * 表字段：id
     */
    private final String FIELD_ID = "_id";

    /**
     * 表字段：下载地址url
     */
    private final String FIELD_URL = "f_a";

    /**
     * 表字段：文件长度
     */
    private final String FIELD_FILE_LENGTH = "f_b";

    /**
     * 表字段：保存路径
     */
    private final String FIELD_SAVE_PATH = "f_c";

    /**
     * 表字段：启动下载的线程数
     */
    private final String FIELD_THREAD_COUNT = "f_d";

    /**
     * 表字段：该URL是否支持断点续传
     */
    private final String FIELD_SUPPORT_RANGES = "f_e";

    private DownloadFileInfoTbl(){}

    public static DownloadFileInfoTbl getInstance(){
        if(instance == null){
            synchronized (DownloadFileInfoTbl.class){
                if(instance == null){
                    instance = new DownloadFileInfoTbl();
                }
            }
        }
        return instance;
    }

    /**
     * 插入
     *
     * @param downloadFileInfo
     */
    public void insert(DownloadFileInfo downloadFileInfo){
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("INSERT INTO ").append(TBL_NAME).append("(")
                .append(FIELD_URL).append(",")
                .append(FIELD_SAVE_PATH).append(",")
                .append(FIELD_FILE_LENGTH).append(",")
                .append(FIELD_SUPPORT_RANGES).append(",")
                .append(FIELD_THREAD_COUNT).append(") VALUES(?, ?, ?, ?, ?);");
        DbHelper.getInstance().getSqliteDatabase().execSQL(sqlBuilder.toString(),
                new Object[]{downloadFileInfo.getUrl(), downloadFileInfo.getSavePath(),
                        downloadFileInfo.getFileLength(), downloadFileInfo.isSupportRanges(), downloadFileInfo.getThreadCount()});
    }

    /**
     * 删除
     *
     * @param url
     */
    public void delete(String url, String savePath){
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("DELETE FROM ").append(TBL_NAME).append(" WHERE ")
                .append(FIELD_URL).append(" = ? AND ").append(FIELD_SAVE_PATH).append(" = ?;");
        DbHelper.getInstance().getSqliteDatabase().execSQL(sqlBuilder.toString(),
                new Object[]{url, savePath});
    }

    /**
     * 查询
     *
     * @param url
     * @return
     */
    public DownloadFileInfo select(String url, String savePath){
        DownloadFileInfo downloadFileInfo = null;
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("SELECT * FROM ").append(TBL_NAME).append(" WHERE ")
                .append(FIELD_URL).append(" = ? AND ").append(FIELD_SAVE_PATH).append(" = ?;");
        Cursor cursor = DbHelper.getInstance().getSqliteDatabase().rawQuery(sqlBuilder.toString(),
                new String[]{url, savePath});
        if(cursor.moveToNext()){
            downloadFileInfo = new DownloadFileInfo();
            downloadFileInfo.set_id(cursor.getInt(cursor.getColumnIndex(FIELD_ID)));
            downloadFileInfo.setUrl(cursor.getString(cursor.getColumnIndex(FIELD_URL)));
            downloadFileInfo.setSavePath(cursor.getString(cursor.getColumnIndex(FIELD_SAVE_PATH)));
            downloadFileInfo.setFileLength(cursor.getInt(cursor.getColumnIndex(FIELD_FILE_LENGTH)));
            downloadFileInfo.setThreadCount(cursor.getInt(cursor.getColumnIndex(FIELD_THREAD_COUNT)));
            downloadFileInfo.setSupportRanges(cursor.getInt(cursor.getColumnIndex(FIELD_SUPPORT_RANGES)) == 1 ? true : false);
        }
        cursor.close();

        return downloadFileInfo;
    }

    /**
     * 新增列：是否支持断点续传
     * @param db
     */
    public void addColumnSupportRanges(SQLiteDatabase db){
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("ALTER TABLE ").append(TBL_NAME).append(" ADD ")
                .append(FIELD_SUPPORT_RANGES).append(" INTEGER DEFAULT 0");
        db.execSQL(sqlBuilder.toString());
    }

    /**
     * 创建表
     *
     * @param db
     */
    public void createTbl(SQLiteDatabase db){
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("CREATE TABLE IF NOT EXISTS ").append(TBL_NAME).append("(")
                .append(FIELD_ID).append(" INTEGER PRIMARY KEY AUTOINCREMENT,")
                .append(FIELD_URL).append(" TEXT,")
                .append(FIELD_FILE_LENGTH).append(" INTEGER,")
                .append(FIELD_SAVE_PATH).append(" TEXT,")
                .append(FIELD_THREAD_COUNT).append(" INTEGER,")
                .append(FIELD_SUPPORT_RANGES).append(" INTEGER DEFAULT 0")
                .append(");");
        db.execSQL(sqlBuilder.toString());
    }

    /**
     * 删除表
     *
     * @param db
     */
    public void dropTbl(SQLiteDatabase db){
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("DROP TABLE IF EXISTS ").append(TBL_NAME);
        db.execSQL(sqlBuilder.toString());
    }
}
